# -*- coding: utf-8 -*-

import urllib
import logging
import urllib2

import xml.etree.ElementTree as ElementTree

import html5lib
from html5lib import treebuilders, treewalkers, serializer

from onlinebrary.lib.aggregator.abstract_aggregator import AbstractAggregator
from onlinebrary.model.agg_data import AggregatedData

log = logging.getLogger(__name__)

SEARCH_URL = 'http://lib.aldebaran.ru/search/'
KEYWORDS_PARAM = 'search'
#PAGE_PARAM = 'page'
CONTENT_ENCODING = 'cp1251'
REQUEST_ENCODING = 'cp1251'

class AldebaranRuAggregator(AbstractAggregator):
    
    def __init__(self):
        self.name = "Lib.Aldebaran.ru"

    def search_by_title(self, title):
    
        data = AggregatedData(self.name)
        
        log.info('Searching %s in %s', title, self.name)
        
    
        title_encoded = title.encode(REQUEST_ENCODING)
        
        query = urllib.urlencode(((KEYWORDS_PARAM, title_encoded),))
        url = SEARCH_URL
        log.info('Requesting search URL: %s', url)
        
        data.source_search = url
        
        p = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("etree", ElementTree))
        try:
            tree = p.parse(urllib2.urlopen(url, query).read())
        except Exception, e:
            log.error(e)
            return e
            
        results = dict()
        results[""] = []
        results_count = 0
        serie_name = ""
        divs = tree.findall(r'.//div')
        for div in divs:
            #if div.attrib.has_key('class') and div.attrib['class'] == 'serie':
            #        serie_name = div.find('h3').text
            #        if div.find('h3/small'):
            #            serie_name += (" <small>%s</small>" % div.find('h3/small').text)
            #        results[serie_name] = []
            if div.attrib.has_key('class') and div.attrib['class'] == 'FULBOK':
                link_element = div.find('b/a')
                if not link_element:
                    continue
                link = link_element.attrib['href']
                title = link_element.find('strong').text
                
                res_link = "<a href='%s' target='_blank'>%s</a>" % (link, title)
                
                '''try:
                    author_element = div.find('small/a')
                    author_link = author_element.attrib['href']
                    author_name = author_element.text
                    res_link += "&nbsp;&nbsp;<a href=\"%s\">%s</a>" % (author_link, author_name)
                finally:'''
                results[""].append(res_link)
                results_count += 1

        data.count = results_count
        data.data = results
        
        return data
        
